package com.qying.test;

import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class MultiRecursiveTaskDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        int[] arrs = new int[999];
        Random random = new Random();

        System.out.println(random.nextInt(100));

       /* int total = 0;
        for (int i = 0; i < arrs.length; i++) {
            int temp = random.nextInt(100);
            total += (arrs[i] = temp);
        }

        System.out.println("普通主线程计算出来的总和 = " + total);
        System.out.println("CPU内核数 = " + Runtime.getRuntime().availableProcessors());

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Integer> future = forkJoinPool.submit(new RecursiveTaskDemo(arrs, 0, arrs.length));

        System.out.println("总和=" + future.get());

        forkJoinPool.shutdown();*/
    }
}

class RecursiveTaskDemo extends RecursiveTask<Integer> {

    private static final int MAX = 70;
    private int arr[];
    private int start;
    private int end;

    public RecursiveTaskDemo(int[] arr, int start, int end) {
        this.arr = arr;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {

        int sum = 0;
        if ((end - start) < MAX) {
            long nanotime = System.nanoTime();
            System.out.println(Thread.currentThread().getName() + " nanotime = " + nanotime + " end - start = " + end + " - " + start + " = " + (end - start));
            for (int i = start; i < end ; i++){
                sum += arr[i];
            }
            return sum;
        } else {

            int middle = (start + end) / 2;
            long nanotime = System.nanoTime();
            System.out.println(Thread.currentThread().getName() + " nanotime = " + nanotime + "  =====任务分解======  " + " middle - start = " + middle + " - " + start + " = " + (middle - start) + "   " + " end - middle = " + end + " - " + middle + " = " + (end - middle));
            RecursiveTaskDemo left = new RecursiveTaskDemo(arr, start, middle);
            RecursiveTaskDemo right = new RecursiveTaskDemo(arr, middle, end);

            left.fork();
            right.fork();

            return left.join() + right.join();
        }
    }
}
